blog

Home / DeveloperSection / Blogs / Indexer in C#

Indexer in C#

priyanka kushwaha2461 11-Mar-2015

In this blog, I’m explaining about Indexer in C#

  •  An indexer allows the programmer to create a class that can act like virtual arrays.
  • We can access instances of those classes using the [] array access operator.
  • An indexer can have private, public, protected or internal modifier & the return type can be any valid C# types.   
  • An indexer in c# must have at least one parameter.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace IndexersExample
{
  
    classProgram
    {
        static public string[] namelist = newstring[0];
        public string this[int index]
        {
            get
            {
                string temp;
                if (index >= 0 && index < namelist.Length)
                    temp = namelist[index];
                else
                    temp = "";
                return (temp);
            }
            set
            {
                if (index >= 0&& index < namelist.Length) namelist[index] = value;
            }
        }
staticvoid Main(string[]args)
        {
            Programobj = newProgram();
            int size;
            Console.WriteLine("Enter Array size");
            size=Convert.ToInt32(Console.ReadLine());
            namelist = newstring[size];
            for (int i = 0; i <namelist.Length; i++)
            {
                Console.WriteLine("Enter string");
                obj[i] = Console.ReadLine();
            }
            Console.WriteLine("----------Output---------");
            for (int i = 0; i <= namelist.Length; i++)
            {
                Console.WriteLine(obj[i]);
            }
            Console.ReadKey();
        }
    }
}
 
Output:
Enter Array size
3
Enter string
Abc
Enter string
Xyz
Enter string
Opq
----------Output-------------
A
Xyz
Opq

 


Updated 22-Feb-2018

Leave Comment

Comments

Liked By